package init

import (
	"fmt"
	"github.com/go-redis/redis"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"homework/global"
	"homework/intelnal/model"
)

func init() {
	ConfigInit()
	DBInit()
	RdbInit()
}

// 配置初始化
func ConfigInit() {
	viper.SetConfigFile("C:\\Users\\李棒111\\GolandProjects\\homework\\applicatiion.yaml")

	err := viper.ReadInConfig()
	if err != nil {
		fmt.Println("配置文件读取失败")
		return
	}
	err = viper.Unmarshal(&global.GlobalConfig)
	if err != nil {
		fmt.Println("配置文件解析失败")
		return
	}
	fmt.Println(global.GlobalConfig)
}

func DBInit() {
	var err error
	conf := global.GlobalConfig.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True", conf.User, conf.Password, conf.Host, conf.Port, conf.Database)
	global.DB, err = gorm.Open(mysql.Open(dsn))
	if err != nil {
		fmt.Println("mysql连接失败")
		return
	} else {
		fmt.Println("mysql连接成功")
	}
	global.DB.AutoMigrate(&model.User{})
}

var Rdb *redis.Client

func RdbInit() {
	Rdb = redis.NewClient(&redis.Options{
		Addr:     global.GlobalConfig.Redis.Host,
		Password: global.GlobalConfig.Redis.Password,
		DB:       0,
	})
	err := Rdb.Ping().Err()
	if err != nil {
		panic(err)
	}
	fmt.Println("redis连接成功")
}
